//
//  RMOneWordPictureVC.m
//  水印
//
//  Created by lanou3g on 16/4/23.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "RMOneWordPictureVC.h"
#import "RMOneWordPictureImageView.h"
#import "UIBarButtonItem+Extension.h"
#import <UIKit/UIKit.h>
#import "PECropViewController.h"
#import "UIImage+RMaddWordToImage.h"
#import "UIView+Extension.h"

@interface RMOneWordPictureVC ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>{


}
@property(nonatomic,strong)RMOneWordPictureImageView *imgView;
@property(nonatomic,strong)UILabel * hintLabel;
@property(nonatomic,strong)UIBarButtonItem * pictureBtn;
@property(nonatomic,strong)UIBarButtonItem * saveBtn;
@property (nonatomic, retain) UIImagePickerController * imagePicker;
@property(nonatomic,strong)UIActionSheet * choosePicture ;
@property (nonatomic) UIPopoverController *popover;

@end

@implementation RMOneWordPictureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"水印图片";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kRealValue(17)],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //左button : 返回
    UIBarButtonItem * backButton = [UIBarButtonItem itemWithImage:@"back"  hightImage:@"back_hl" target:self action:@selector(backMainVCAction)];
    self.navigationItem.leftBarButtonItem = backButton;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor redColor];
    //导航栏按钮
    self.pictureBtn = [UIBarButtonItem itemWithImage:@"picture"  hightImage:@"picture_hl" target:self action:@selector(addPicture:)];
    self.navigationItem.rightBarButtonItem = self.pictureBtn;
    self.saveBtn = [UIBarButtonItem itemWithImage:@"save"  hightImage:@"save_hl" target:self action:@selector(savePicture:)];
    self.navigationItem.rightBarButtonItem = self.saveBtn;
    self.navigationItem.rightBarButtonItems = @[self.saveBtn,self.pictureBtn];
    
    //要添加图的imageView
    self.imgView = [[RMOneWordPictureImageView alloc]initWithFrame:CGRectMake(20, kBarHeight + 10, kScreenWidth - 40 , 300)];
//    self.imgView.backgroundColor = [UIColor colorWithWhite: 0.9 alpha: 1];
    self.imgView.backgroundColor = [UIColor whiteColor];
    self.imgView.userInteractionEnabled = YES;
    self.imgView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.imgView];
    
    //提示用户的label
    self.hintLabel = [[UILabel alloc] init];
    self.hintLabel.frame = CGRectMake(0, 0, 280, 30);
    self.hintLabel.center = CGPointMake(self.imgView.frame.size.width / 2, self.imgView.frame.size.height / 2);
    self.hintLabel.text = @"点击添加图片,单击图片可添加文字";
    self.hintLabel.textAlignment = NSTextAlignmentCenter;
    self.hintLabel.textColor = kRMBarTintColor;
    [self.imgView addSubview: self.hintLabel];
    UITapGestureRecognizer *imageViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewTapped)];
    imageViewTap.delegate = self;
    [self.imgView addGestureRecognizer:imageViewTap];
    [self.imgView setUserInteractionEnabled:YES];
    

}




//mark!!!:返回按钮
-(void)backMainVCAction{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    // 注册键盘出现通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object: nil];
    // 注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidHide:) name: UIKeyboardDidHideNotification object: nil];

}

-(void)dealloc{
    // 解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver: self name: UIKeyboardDidShowNotification object: nil];
    // 解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver: self name: UIKeyboardDidHideNotification object: nil];
}

- (void)keyboardDidShow:(NSNotification *)notif{
     self.imgView.y = 10;
    [self.imgView.wordTextField becomeFirstResponder];
}

- (void)keyboardDidHide:(NSNotification *)notif
{
  
     self.imgView.center = CGPointMake(kScreenWidth/2, kScreenHeight/2 - 44);
    [self.imgView.wordTextField resignFirstResponder];
    
}

#pragma mark:----------获取图片------------
-(void)imageViewTapped{

    
    if (self.imgView.image != nil) {
        
        self.imgView.wordTextField.hidden = NO;
        
        
        if(self.imgView.wordTextField.text.length > 20) {
            // 超出字数限制（15字），弹出提示框
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle: @"输入文字太长" message: @"限制20个字" delegate: self cancelButtonTitle: @"确定" otherButtonTitles: nil, nil];
            [alter show];
        }
        
        if([self.imgView.wordTextField isFirstResponder]){
            [self.imgView.wordTextField resignFirstResponder];
            self.imgView.wordTextField.alpha = ([self.imgView.wordTextField.text isEqualToString:@""]) ? 0 : self.imgView.wordTextField.alpha;
        } else {
            [self.imgView.wordTextField becomeFirstResponder];
            self.imgView.wordTextField.alpha = 1;
        }
    }else{
    [self addPicture:self.imgView];
    }

}

-(void)addPicture:(id)sender{
     if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    self.choosePicture = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"手机相册", nil];
}else{
    
    self.choosePicture = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"手机相册", nil];
}
self.choosePicture.tag = 1000;
[self.choosePicture showInView:self.view];
}

#pragma mark 懒加载imagePicker
- (UIImagePickerController *)imagePicker
{
    if(!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

#pragma mark - UIActionSheetDelegate协议，选择相册进入相册
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //判断是否支持拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
            switch (buttonIndex) {
                case 0:
                    //图片来源于相机拍照
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //图片来源于本地相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }else{
            if (buttonIndex == 1) {
                return;
            }else{
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        self.imagePicker.sourceType = sourceType;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }
}

#pragma mark - 相册的访问
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage * originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        self.imgView.image = originImage;
        [picker dismissViewControllerAnimated:YES completion:^{
            //调用剪裁
            [self openEditor:nil];
        }];

        picker = nil;
        //去掉label
        [self.hintLabel removeFromSuperview];
    }
}
//mark!!!: 图片压缩
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

//    //MARK!!!:第三方剪裁图片
-(void)openEditor:(id)sender{
    PECropViewController * PEVC = [[PECropViewController alloc]init];
    PEVC.delegate = self;
    PEVC.image = self.imgView.image;
    //选择图片后 剪裁框的出现
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:PEVC];
    [self presentViewController:navigationController animated:YES completion:NULL];
}

#pragma mark -  剪裁-----
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage
{
    [controller dismissViewControllerAnimated:YES completion:NULL];
    
//    CGRect frame = self.imgView.frame;
//    frame.size = croppedImage.size;
//    self.imgView.frame = frame;
//    self.imgView.image = croppedImage;
    
    if (croppedImage.size.width >= kScreenWidth-20 && croppedImage.size.height >= kScreenHeight - 84) {
        CGFloat imgW = kScreenWidth - 20;
        CGFloat imgH = croppedImage.size.height;
        croppedImage = [self scaleToSize:croppedImage size:CGSizeMake(imgW, imgH)];
//
//    }
//    if (croppedImage.size.height >= kScreenHeight - 84) {
        CGFloat imgHH = kScreenHeight - 84;
        CGFloat imgWW = croppedImage.size.width;
        croppedImage = [self scaleToSize:croppedImage size:CGSizeMake(imgWW, imgHH)];
//        self.imgView.image = croppedImage;
        self.imgView.frame = CGRectMake(10, kBarHeight, croppedImage.size.width, croppedImage.size.height - 30);
        self.imgView.center = CGPointMake(kScreenWidth/2, kScreenHeight/2 - 44);
    }
 
    
//
    self.imgView.image = croppedImage;
//    self.imgView.frame = CGRectMake(0, 0, croppedImage.size.width, croppedImage.size.height);
//    self.imgView.wordTextField.frame =CGRectMake(0, croppedImage.size.height - 30, croppedImage.size.width, 30);

}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller
{
    [controller dismissViewControllerAnimated:YES completion:NULL];
    
}

#pragma mark ------文字添加到图片上-----
//加文字水印

- (UIImage *)addText:(UIImage *)img text:(NSString *)mark withRect:(CGRect)rect{
    
    int w = img.size.width;
    int h = img.size.height;
    UIGraphicsBeginImageContext(img.size);
    [[UIColor cyanColor] set];
    [img drawInRect:CGRectMake(0, 0, w, h)];
    if([[[UIDevice currentDevice]systemName]floatValue] >= 7.0){
        NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Heiti SC" size:kRealValue(15)], NSFontAttributeName,[UIColor blueColor] ,NSForegroundColorAttributeName,nil];
        
//        [mark drawAtPoint:rect withAttributes:dic];
   
        [mark drawInRect:rect withAttributes:dic];
}else{
//      //该方法在7.0及其以后都废弃了
        [mark drawInRect:rect withFont:[UIFont fontWithName:@"Heiti SC" size:kRealValue(15)]];
    }
    UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return aimg;
    
}

#pragma mark:----------保存图片------------
-(void)savePicture:(id)sender{
    // 1.检测是否有图片
    UIImage * newImage = [self addText:self.imgView.image text:self.imgView.wordTextField.text withRect:self.imgView.wordTextField.frame];
    UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
  
}

#pragma mark - 将图片保存
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *) contextInfo
{
    NSLog(@"error = %@",error);
    // 保存到相册之后会调用这个方法
    // 在保存完成之后，应该弹出用户提示框，并且在没有出错的情况下弹出成功信息
    if(error == nil) {
        // 弹出成功信息
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle: @"保存成功" message: @"保存到相册成功!" delegate: self cancelButtonTitle: @"确定" otherButtonTitles: nil, nil];
        [alter show];
        // 成功之后，将文字清空
        self.imgView.wordTextField.text = nil;
    } else {
        // 弹出失败信息
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle: @"保存失败" message: @"保存失败!" delegate: self cancelButtonTitle: @"确定" otherButtonTitles: nil, nil];
        [alter show];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
